package cn.com.ylpw.web.special.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Maps;

import cn.com.ylpw.exception.GlobalException;
import cn.com.ylpw.entity.Success;
import cn.com.ylpw.spring.SpringController;
import cn.com.ylpw.web.customer.service.ICustomerService;
import cn.com.ylpw.web.special.service.ISpecialService;

import cn.com.ylpw.utils.StringUtils;
@Controller("specialController")
@RequestMapping("/special/")
public class SpecialController extends SpringController {

	@Autowired
	@Qualifier("customerService")
	private ICustomerService customerService;
	
	@Autowired
	@Qualifier("specialService")
	private ISpecialService specialService;
	
	@RequestMapping("findInitLottery")
	@ResponseBody
	public Map<String,Object> findInitLottery(@RequestParam("activityName") String activityName,
			Integer customersId,boolean currentDate) throws GlobalException{
		Map<String,Object> _data = Maps.newHashMap();
		ModelAndView mv = new ModelAndView();
		if(StringUtils.isBlank(activityName)){
			throw new GlobalException(Success.getInstance(false, "5009", "活动名称不能为空"));
		}
		// 用户可以抽奖的奖品
		List<Map<String, Object>> lottery = specialService.findLotteryByName(activityName);// 用户可以抽奖的奖品
		if(StringUtils.isBlank(activityName)){
			throw new GlobalException(Success.getInstance(false, "5010", "找不到奖区奖品"));
		}
		//查询所有中奖名单 
		List<Map<String, Object>> LotteryLuckList  = specialService.findLotteryLuckAll(null, activityName);
		Random random = new Random();
		int a = 0,b = 0;
		Map<String, Object> defaultLottery = new HashMap<String, Object>();// 用户中没中奖的相关参数
		for (int i = 0; i < lottery.size(); i++) {
			double alottery = Double.parseDouble(lottery.get(i).get("num").toString());
			double lot = Double.parseDouble((lottery.get(i).get("probability").toString()));
			if (alottery <= 0) {// 积分商品库存不足也不能抽中
				continue;
			}
			if (lot == 0) {// 中奖机率为0也不能抽中
				continue;
			}
			a = random.nextInt((int) (100 / lot));
			b = random.nextInt((int) (100 / lot));
			if (a == b) {
				defaultLottery = lottery.get(i);
				break;
			}
		}
		if(StringUtils.isEmpty(defaultLottery)){
			defaultLottery = specialService.findLotteryByNameAndId(activityName, null);
			if(StringUtils.isEmpty(defaultLottery)){
				defaultLottery = specialService.findDefaultLotteryByName(activityName,"券");
			}
		}
		
		int lotterynum = 0;
		if(!StringUtils.isBlank(customersId)){
			Map<String,Object> customers = customerService.findCustomersById(customersId);
			//重新将用户能抽的次数带到页面
			if (!StringUtils.isEmpty(customers)) {
				lotterynum = specialService.findLotteryNum(customersId, activityName,currentDate);
			}			
		}
		_data.put("LotteryLuckList", LotteryLuckList);
		_data.put("LotteryList", lottery);
		_data.put("lotteryMap", defaultLottery);
		_data.put("lotterynum", lotterynum);
		return _data;
		
	}
	
	@RequestMapping("/savelottery")
	@ResponseBody
	public Map<String,Object> savelottery(@RequestParam("activityName") String activityName,//活动名称
			@RequestParam("zhongjiang") String zhongjiang,//是否中奖
			@RequestParam("id") String id,//奖品id
			@RequestParam("customersId") String customersId//客户id
			){
		Map<String,Object> _data = Maps.newHashMap();
		//查询用户是否中过奖
		Integer isLotteryNum = specialService.hasLottery(Integer.valueOf(customersId),activityName);
		if(isLotteryNum>0){
			zhongjiang = "0";
		}
		Integer lotteryid = specialService.findlotteryId(Integer.valueOf(id));
		Integer zhongjiang1 = specialService.savelottery(Integer.valueOf(customersId), 0, Integer.valueOf(zhongjiang), Integer.valueOf(id), lotteryid);
		_data.put("zhongjiang", zhongjiang1);
		return _data;
	}
	
	@RequestMapping("/getCoupons")
	@ResponseBody
	public Map<String,Object> getCoupons(@RequestParam("coupons") String coupons,
			@RequestParam("customersId") String customersId,
			@RequestParam("startTime") String startTime,
			@RequestParam("endTime") String endTime,boolean repeatFlag){
		Map<String,Object> result = Maps.newHashMap();
		if(customersId == null) {
			result.put("success", false);		// 需要跳转到登陆页面
			result.put("msg", "NO_LOGIN");
			return result;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			long start  = sdf.parse(startTime).getTime();
			long end  = sdf.parse(endTime).getTime();
			long cur  = sdf.parse(sdf.format(new Date())).getTime();
			if(start  > cur ) {
				result.put("success", false);
				result.put("msg", "活动尚未开始，敬请期待");
				return result;
			}
			if(end  < cur ) {
				result.put("success", false);
				result.put("msg", "活动结束");
				return result;
			}	

			Map<String,Object> params = Maps.newHashMap();
			params.put("customerId",customersId);
			// 获取现金券列表
			params.put("couponId", coupons);
			params.put("curMsg", "你已经领取过了");
			params.put("assigneduser","SYSTEM");
			params.put("successMsg", "领取成功");
			params.put("noQty", "券已发完");
			params.put("errMsg","领取的人数太多，请稍后重试");
			
			result = specialService.updateCoupons(params);
			
		}catch (Exception e) {
			result.put("success", false);
			result.put("msg", e.getMessage());
		}
		return result;
	}
	
}
